package com.mosai.alignpro.util;

import android.text.TextUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;

/**
 * Created by Rays on 2020/3/26.
 */
public final class DateUtils {
    private static final TimeZone TIME_ZONE_UTC = TimeZone.getTimeZone("GMT+0:00");

    private static final ThreadLocal<SimpleDateFormat> utcDateFormat = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            SimpleDateFormat utcFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault());
            utcFormat.setTimeZone(TIME_ZONE_UTC);
            return utcFormat;
        }
    };

    private static final Map<String, ThreadLocal<SimpleDateFormat>> threadLocalMap = new HashMap<>();
    public static final String PATTERN_AUDIT = "yyyy.MM.dd HH:mm:ss";

    private static SimpleDateFormat getSimpleDateFormat(String pattern) {
        synchronized (threadLocalMap) {
            ThreadLocal<SimpleDateFormat> threadLocal = threadLocalMap.get(pattern);
            if (threadLocal == null) {
                threadLocal = new ThreadLocal<SimpleDateFormat>() {
                    @Override
                    protected SimpleDateFormat initialValue() {
                        return new SimpleDateFormat(pattern, Locale.getDefault());
                    }
                };
                threadLocalMap.put(pattern, threadLocal);
            }
            return threadLocal.get();
        }
    }

    public static String format(String pattern, long time) {
        return getSimpleDateFormat(pattern).format(time);
    }

    public static String format(String pattern, Date date) {
        return getSimpleDateFormat(pattern).format(date);
    }

    @SuppressWarnings("ConstantConditions")
    public static String formatAuditDate(String date) {
        if (TextUtils.isEmpty(date)) {
            return "";
        }
        try {
            Date parse = utcDateFormat.get().parse(date);
            return format(PATTERN_AUDIT, parse);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    public static String formatAuditDate(Date date) {
        if (date == null) {
            return "";
        }
        return format(PATTERN_AUDIT, date);
    }

    @SuppressWarnings("ConstantConditions")
    public static Date parseUTC(String date) {
        if (TextUtils.isEmpty(date)) {
            return null;
        }
        try {
            return utcDateFormat.get().parse(date);
        } catch (Exception e) {
            return null;
        }
    }

}
